import React, { useRef, useState, useEffect } from 'react'
import classNames from 'classnames'
import styles from './index.module.scss'
import Icon from '@/components/Icon'

export default function Img({ className, src, alt }) {
  const imgRef = useRef(null)
  // 控制加载
  const [load, setLoad] = useState(null)
  // 控制是否加载失败
  const [error, setError] = useState(false)

  useEffect(() => {
    // 监听图片
    const observe = new IntersectionObserver(([{ isIntersecting }]) => {
      if (isIntersecting) {
        // 图片在可视区域
        imgRef.current.src = imgRef.current.dataset.src
        // 取消监听
        observe.unobserve(imgRef.current)
      }
    })
    observe.observe(imgRef.current)
  }, [])

  // 加载成功
  const onLoad = () => {
    setError(false)
    setLoad(false)
  }
  // 加载失败
  const onError = () => {
    setLoad(false)
    setError(true)
  }

  return (
    <div className={classNames(styles.root, className)}>
      {/* 加载中 */}
      {load && (
        <div className="image-icon">
          <Icon type="iconphoto" />
        </div>
      )}

      {/* 加载出错时显示的内容 */}
      {error && (
        <div className="image-icon">
          <Icon type="iconphoto-fail" />
        </div>
      )}

      <img
        alt={alt}
        ref={imgRef}
        data-src={src}
        onLoad={onLoad}
        onError={onError}
      />
    </div>
  )
}
